package dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import dao.UserDao;
import entity.User;
import util.JDBCUtil;
import util.ResultSetCreateObj;

public class UserDaoImpl implements UserDao {

	@Override
	public int add(User user) {
		String sql =  "insert into user values(null,?,?,?,?,?)";
		int num = JDBCUtil.executeUpdate(sql, user.getName(),user.getUsername(),user.getPassword(),user.getGender(),user.getTelephone());
		return num;
	}

	@Override
	public int update(User user) {
		String sql =  "update user set username=?,password=?,gender=?,telephone=? where id=? ";
		int num = JDBCUtil.executeUpdate(sql,user.getUsername(),user.getPassword(),user.getGender(),user.getTelephone(),user.getId());
		return num;
	}

	@Override
	public int delete(int id) {
		String sql =  "delete from user where id=?";
		int num = JDBCUtil.executeUpdate(sql, id);
		return num;
	}

	@Override
	public List<User> findAll() {
		List<User> list = JDBCUtil.executeQuery("select * from user", new ResultSetCreateObj<User>() {

			@Override
			public User create(ResultSet rs) {
				User u = new User();
				try {
					u.setId(rs.getInt("id"));
					u.setGender(rs.getString("gender"));
					u.setName(rs.getString("name"));
					u.setUsername(rs.getString("username"));
					u.setPassword(rs.getString("password"));
					u.setTelephone(rs.getString("telephone"));
					return u;
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return u;
			}
		});
		
		return list;
	}

	@Override
	public List<User> findLikeName(String name) {
		List<User> list = JDBCUtil.executeQuery("select * from user where username like ?", new ResultSetCreateObj<User>() {

			@Override
			public User create(ResultSet rs) {
				User u = new User();
				try {
					u.setId(rs.getInt("id"));
					u.setGender(rs.getString("gender"));
					u.setName(rs.getString("name"));
					u.setUsername(rs.getString("username"));
					u.setPassword(rs.getString("password"));
					u.setTelephone(rs.getString("telephone"));
					return u;
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return u;
			}
		},"%"+name+"%");
		
		return list;
	}

}
